﻿using System;
using System.Reflection;

namespace ElectronicCommerce.Framework.Core
{
    /// <summary>
    /// Singleton Provider
    /// </summary>
    /// <typeparam name="T">T</typeparam>
    public class SingletonProvider<T> where T : class 
    {
        SingletonProvider()
        {
        }

        /// <summary>
        /// Singleton Creator
        /// </summary>
        class SingletonCreator
        {
            static  SingletonCreator()
            {
            }

            public static  T CreateInstance()
            {
                ConstructorInfo constructorInfo = typeof (T).GetConstructor(
                    BindingFlags.Instance|BindingFlags.NonPublic,
                    Type.DefaultBinder,
                    Type.EmptyTypes,
                    null
                    );
                if (constructorInfo != null)
                {
                    return constructorInfo.Invoke(null) as T;
                }
                else
                {
                    // alternatively, throw an exception indicating the type parameter
                    // should have a private parameterless constructor)
                    throw new NotImplementedException("Type parameter should have a private parameterless constructor.");
                }
            }

            internal static readonly T Instance = CreateInstance();
        }

        public static  T UniqueInstance
        {
            get { return SingletonCreator.Instance; }
        }
    }
}
